package com.kly.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @author admin
 * @date 2025/4/6
 */
public class RedisLock {

    private final StringRedisTemplate stringRedisTemplate;

    private static final String LOCK_PREFIX = "lock:";

    private static final String ID_PREFIX = UUID.randomUUID().toString(true);

    public RedisLock(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 尝试获取锁
     * @param id
     * @param ttl
     * @return
     */
    public boolean tryLock(Long id, Integer ttl) {
        String key = LOCK_PREFIX + id;
        // 设置线程唯一标识
        String threadId = String.format("%s-%s", ID_PREFIX, Thread.currentThread().getId());
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, threadId, ttl, TimeUnit.MINUTES);
        return Boolean.TRUE.equals(flag);
    }

    /**
     * 释放锁
     * @param id
     */
    public void unLock(Long id) {
        String key = LOCK_PREFIX + id;
        String threadIdCache = stringRedisTemplate.opsForValue().get(key);
        String threadId = String.format("%s-%s", ID_PREFIX, Thread.currentThread().getId());
        if(threadId.equals(threadIdCache)) {
            stringRedisTemplate.delete(key);
        }
    }
}
